
package logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class Logger {
	
	// Symbols
	private static final String RIGHT_SQUARE_BRACKET = "] ";
	private static final String LEFT_SQUARE_BRACKET = "[";
	private static final String EMPTY_STRING = "";
	private static final String SLASH = "/";
	
	// Error messages
	private static final String ERROR_FILE = "Error file not found";
	private static final String ERROR_CREATING = "Error creating log file";
	
	// Log file
	private static final String LOG_FILE = "log.txt";
	
	public static ArrayList<String> output = new ArrayList<String>();

	//@author A0096677H
	// Reads existing log file to be used during initialization
	public static void readFromFile() {
		try {
			BufferedReader br = new BufferedReader(new FileReader(LOG_FILE));
			String line = br.readLine();

			while (line != null) {
				output.add(line);
				line = br.readLine();
			}
			br.close();
		} catch (IOException | NumberFormatException | NullPointerException e) {
			System.out.println("Error reading previous log file");
		}
	}
	
	//@author A0096677H
	// Checks if log file exists, add to the list and prints
	public static void add(String content) {
		checkForFileExists();
		output.add(logString(content));
		printToLog(output);
	}

	//@author A0096677H
	// Checks if file exist. If not, then create it
	public static void checkForFileExists() {
		File file = new File(LOG_FILE);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				System.out.println(ERROR_CREATING);
			}
		}
	}
	
	//@author A0096677H
	// Prints entire ArrayList into log file
	public static void printToLog(ArrayList<String> list){
		try {
			PrintWriter pw = new PrintWriter(LOG_FILE);
			for (int i=0; i<list.size(); i++) {
				pw.println(list.get(i));
			}
			pw.close();
		} catch (FileNotFoundException e) {
			System.out.println(ERROR_FILE);
			e.printStackTrace();
		}

	}
	
	//@author A0085082E
	// Prints entire ArrayList into log file
	public static String getCurrentDate(){
		Calendar current = new GregorianCalendar();
		
		String currentDate = EMPTY_STRING;
		
		currentDate = current.get(Calendar.DATE) + SLASH + 
				      current.get(Calendar.MONTH) + SLASH + 
				      current.get(Calendar.YEAR);
		
		return currentDate;
	}
	
	//@author A0085082E
	// Prints the error string in the right format
	public static String logString(String content){
		return LEFT_SQUARE_BRACKET + getCurrentDate() + RIGHT_SQUARE_BRACKET + content;
	}
}
